package top.letscode.study.disconf.refresh;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.classic.util.ContextInitializer;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;
import com.baidu.disconf.client.common.annotations.DisconfUpdateService;
import com.baidu.disconf.client.common.update.IDisconfUpdate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import top.letscode.study.disconf.config.LogbackConfig;

import java.net.URL;

/**
 * @Author: zhengzhq
 * @Date: 2019-08-30 15:22
 * @Description: logback配置更新进行reload
 */
@Service
@DisconfUpdateService(classes = {LogbackConfig.class})
public class LogbackConfigurationRefresher implements IDisconfUpdate {

    private static Logger logger = LoggerFactory.getLogger(LogbackConfigurationRefresher.class);

    public void reload() throws Exception {
        logger.warn("logback configuration changed, start reload now.");
        LoggerContext loggerContext = (LoggerContext)LoggerFactory.getILoggerFactory();

        ContextInitializer ci = new ContextInitializer(loggerContext);
        URL url = ci.findURLOfDefaultConfigurationFile(true);

        try {
            JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(loggerContext);
            loggerContext.reset();
            configurator.doConfigure(url);

            logger.warn("finish reload logback configuration");
        } catch (JoranException e) {
            logger.error("reload logback configuration error!", e);
        }

        // 打印加载配置过程遇到的告警或者错误信息
        StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext);
    }
}
